package cn.org.donald.service.impl;

import cn.org.donald.base.ServiceException;
import cn.org.donald.mapper.PermissionMapper;
import cn.org.donald.pojo.entity.Permission;
import cn.org.donald.security.body.PermissionInfo;
import cn.org.donald.security.util.DonaldUtil;
import cn.org.donald.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Donald
 * @since 2021-03-17
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {


    private static final Logger logger = LoggerFactory.getLogger(PermissionServiceImpl.class);

    @Resource
    private PermissionMapper permissionMapper;


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean sync() {
        // 保留自增id 全量同步
        try {
            List<PermissionInfo> memList = DonaldUtil.getPermissionInfo();
            Iterator<PermissionInfo> iterator = memList.iterator();

            List<Permission> dbList = permissionMapper.selectList(null);
            dbList.forEach(db -> {
                while (iterator.hasNext()) {
                    PermissionInfo mem = iterator.next();
                    // 更新
                    db.setDescription(mem.getPermissionDescription());
                    db.setControllerName(mem.getControllerName());
                    db.setMethodName(mem.getMethodName());
                    db.setPermissionName(mem.getPermissionName());
                    permissionMapper.updateById(db);
                    iterator.remove();
                }
            });
            if (memList.size() > 0) {
                List<Permission> collect = memList.stream().map(mem -> {
                    Permission permission = new Permission();
                    permission.setDescription(mem.getPermissionDescription());
                    permission.setControllerName(mem.getControllerName());
                    permission.setMethodName(mem.getMethodName());
                    permission.setPermissionName(mem.getPermissionName());
                    return permission;
                }).collect(Collectors.toList());
                boolean b = this.saveBatch(collect);
                if (b) {
                    return true;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            logger.info("同步权限记录失败!");
            throw new ServiceException("同步全线信息异常,请重试或联系管理员!");
        }
        return false;
    }
}
